﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StableDiffusionTools.Utils
{
    public static class InterlockedUtil
    {
        public static bool CompareExchangeIfGreaterThan(ref int location, int newValue) => CompareExchangeIfGreaterThan(ref location, newValue, newValue);
        public static bool CompareExchangeIfGreaterThan(ref int location, int comparison, int newValue)
        {
            int initialValue;
            do
            {
                initialValue = location;
                if (initialValue >= comparison) return false;
            }
            while (Interlocked.CompareExchange(ref location, newValue, initialValue) != initialValue);
            return true;
        }
        public static bool CompareExchangeIfLessThan(ref int location, int newValue) => CompareExchangeIfLessThan(ref location, newValue, newValue);
        public static bool CompareExchangeIfLessThan(ref int location, int comparison, int newValue)
        {
            int initialValue;
            do
            {
                initialValue = location;
                if (initialValue <= comparison) return false;
            }
            while (Interlocked.CompareExchange(ref location, newValue, initialValue) != initialValue);
            return true;
        }
    }
}
